package com.component.api.model.dto;

import cn.hutool.core.collection.CollUtil;
import com.component.api.function.OperationFunction;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 * 归一列
 * @author xianggj
 * @Date 2021/11/29 13:56
 **/
@Data
@NoArgsConstructor
public class ToAcolumnDTO extends ColumnDTO  implements Serializable {
    private static final long serialVersionUID = -1L;


    /**
     * 归一规则
     */
    private List<Rule> rules;


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Rule implements Serializable {

        private static final long serialVersionUID = -1L;

        /**
         * 主值
         */
        private Double mainVal;

        /**
         * 开始值
         */
        private Double startVal;

        /**
         * 结束值
         */
        private Double endVal;
    }

    public void addRules(Rule rule) {
        if (this.rules == null){
            this.rules = new ArrayList<>();
        }
        this.rules.add(rule);
    }

    /**
     * 获取计算公式
     * @return
     */
    public OperationFunction getFunction(){
        if (CollUtil.isEmpty(rules)) {
            return e -> e;
        } else {
            return e-> {
                for (Rule rule: rules) {
                    e =  applyRule(e, rule);
                }
                return e;
            };
        }
    }

    /**
     * 应用规则
     * @param e
     * @param rule
     * @return
     */
    private double applyRule(double e, Rule rule) {
        if (rule.startVal == null){
            rule.startVal = Double.MIN_VALUE;
        }
        if (rule.endVal == null){
            rule.endVal = Double.MAX_VALUE;
        }
        if (e >= rule.startVal && e < rule.endVal){
            return rule.mainVal;
        }
        return e;
    }
}
